package com.mesd.killer.importer;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class GameResultManager
{
	public static final String SCORE_SEP = "-";

	public static final String NEW_SEASON = "2012-2013";

	public static final String LEAGUE_NAME = "德巴";

	public HashMap<Integer, String> teamMap = new HashMap();

	public static final HashMap leagueIdList = new HashMap();

	public static final String propertiesFileName = "newLeagueSaichen.properties";

	public static void main(String[] args)
		throws Exception
	{
		GameResultManager manager = new GameResultManager();
//		manager.importNewLeagueSaichen();
//		manager.updateGameResultBySB();
//		manager.updateGameResultByBet365();
		 manager.parseURL(LEAGUE_NAME,"http://info.bet007.com/jsData/matchResult/2012-2013/s1256.js");
//		 manager.parseURL(LEAGUE_NAME,"http://info.bet007.com/jsData/matchResult/2011-2012/s692.js");
//		 manager.parseURL(LEAGUE_NAME,"http://info.bet007.com/jsData/matchResult/2010-2011/s692.js");
//;
//		 manager.parseURL(LEAGUE_NAME,"http://info.bet007.com/jsData/matchResult/2010/s596_61.js");
//		 manager.parseURL(LEAGUE_NAME,"http://info.bet007.com/jsData/matchResult/2010/s596_60.js");
	}

	static
	{
		leagueIdList.put(
			1256, "德巴");
		leagueIdList.put(
			125, "德南");
		leagueIdList.put(
			692, "德西");
		leagueIdList.put(
			126, "德北");
		leagueIdList.put(
			469, "阿美超");
		leagueIdList.put(
			353, "爱沙甲");
		leagueIdList.put(
			136, "匈甲");
		leagueIdList.put(
			290, "捷乙");
		leagueIdList.put(
			230, "白俄超");
		leagueIdList.put(
			466, "哈萨超");
		leagueIdList.put(
			766, "越南联");
		leagueIdList.put(
			700, "泰超");
		leagueIdList.put(
			772, "乌兹超");
		leagueIdList.put(
			460, "加拿超");
		leagueIdList.put(
			279, "伊朗超");
		leagueIdList.put(
			250, "哥伦甲");
		leagueIdList.put(
			354, "巴拉甲");
		leagueIdList.put(
			242, "秘鲁甲");
		leagueIdList.put(
			139, "爱甲");
		leagueIdList.put(
			1, "爱超");
		leagueIdList.put(
			381, "冰岛甲");
		leagueIdList.put(
			166, "冰岛超");
		leagueIdList.put(
			504, "哥斯甲");
		leagueIdList.put(
			616, "澳威超");
		leagueIdList.put(
			119, "乌克超");
		leagueIdList.put(
			124, "罗甲");
		leagueIdList.put(
			596, "厄瓜甲");
		leagueIdList.put(
			593, "玻利甲");
		leagueIdList.put(
			221, "波兰甲");
		leagueIdList.put(
			235, "俄甲");
		leagueIdList.put(
			137, "捷甲");
		leagueIdList.put(
			2, "阿甲");
		leagueIdList.put(
			273, "澳洲甲");
		leagueIdList.put(
			436, "澳维超");
		leagueIdList.put(
			3, "奥甲");
		leagueIdList.put(
			128, "奥乙");
		leagueIdList.put(
			4, "巴西甲");
		leagueIdList.put(
			358, "巴西乙");
		leagueIdList.put(
			5, "比甲");
		leagueIdList.put(
			138, "比乙");
		leagueIdList.put(
			6, "波兰超");
		leagueIdList.put(
			7, "丹超");
		leagueIdList.put(
			127, "丹甲");
		leagueIdList.put(
			8, "德甲");
		leagueIdList.put(
			9, "德乙");
		leagueIdList.put(
			693, "德丙");
		leagueIdList.put(
			10, "俄超");
		leagueIdList.put(
			11, "法甲");
		leagueIdList.put(
			12, "法乙");
		leagueIdList.put(
			13, "芬超");
		leagueIdList.put(
			212, "芬甲");
		leagueIdList.put(
			15, "韩K联");
		leagueIdList.put(
			16, "荷甲");
		leagueIdList.put(
			17, "荷乙");
		leagueIdList.put(
			140, "墨西哥");
		leagueIdList.put(
			21, "美职业");
		leagueIdList.put(
			22, "挪超");
		leagueIdList.put(
			123, "挪甲");
		leagueIdList.put(
			23, "葡超");
		leagueIdList.put(
			157, "葡甲");
		leagueIdList.put(
			25, "日职联");
		leagueIdList.put(
			284, "日乙");
		leagueIdList.put(
			26, "瑞典超");
		leagueIdList.put(
			122, "瑞典甲");
		leagueIdList.put(
			27, "瑞士超");
		leagueIdList.put(
			121, "瑞士甲");
		leagueIdList.put(
			29, "苏超");
		leagueIdList.put(
			30, "土超");
		leagueIdList.put(
			130, "土甲");
		leagueIdList.put(
			31, "西甲");
		leagueIdList.put(
			32, "希腊超");
		leagueIdList.put(
			33, "西乙");
		leagueIdList.put(
			34, "意甲");
		leagueIdList.put(
			240, "乌拉甲");
		leagueIdList.put(
			36, "英超");
		leagueIdList.put(
			37, "英冠");
		leagueIdList.put(
			39, "英甲");
		leagueIdList.put(
			40, "意乙");
		leagueIdList.put(
			415, "智利甲");
	}

	public int getLeagueID(String leagueName)
	{
		int ID = 0;
		Set keys = leagueIdList.keySet();
		for (Iterator<Integer> iterator = keys.iterator(); iterator.hasNext();)
		{
			int key = iterator.next();
			if (leagueName.equalsIgnoreCase((String) leagueIdList.get(key)))
			{
				return key;
			}
		}
		return ID;
	}

	public void insertLeagueTeam(String leagueName, String line, Connection conn)
	{
		try
		{
			// Statement stmt = conn.createStatement();
			int leagueID = getLeagueID(leagueName);
			String[] arrTeams = line.split("=");
			String teams = arrTeams[1];
			String[] arrTeams1 = teams.split("\\]\\,\\[");
			String[] s = arrTeams1[0].split(",");
			int teamID = Integer.parseInt(s[0].substring(3));
			String teamName = s[1].replaceAll(
				"'", "").trim();
			teamMap.put(
				teamID, teamName);
			// String sql = "insert into league_team values(" + leagueID + ",'"
			// + LEAGUE_NAME + "',"
			// + teamID + ",'" + teamName + "')";
			// stmt.addBatch(sql);
			for (int i = 1; i < arrTeams1.length; i++)
			{
				s = arrTeams1[i].split(",");
				teamID = Integer.parseInt(s[0]);
				teamName = s[1].replaceAll(
					"'", "").trim();
				teamMap.put(
					teamID, teamName);
				// sql = "insert into league_team values(" + leagueID + ",'" +
				// LEAGUE_NAME + "',"
				// + teamID + ",'" + teamName + "')";
				// stmt.addBatch(sql);
			}
			// stmt.executeBatch();
			// stmt.close();
		}
		catch (Exception e)
		{
			// e.printStackTrace();
		}
	}

	public void parseURL(String leagueName, String urlString)
	{
		Connection conn = DBUtil.getConnection();
		Statement stmt = null;
		try
		{
			stmt = conn.createStatement();
			URL url = new URL(urlString);
			InputStream inputStream = (InputStream) url.getContent();
			BufferedReader da = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			String line = da.readLine();
			do
			{
				line = da.readLine();
				System.out.println(line);
				if (line.startsWith("var arrTeam"))
				{
					insertLeagueTeam(
						leagueName, line, conn);
				}
				if (line.startsWith("jh"))
				{
					if (line.length() < 20)
					{
						continue;
					}
					String[] ss = line.split("=");
					String[] sss = ss[0].split("_");

					String round = sss[1].replaceAll(
						"\"]", "").trim();
					String[] ssss = ss[1].split("\\]\\,\\[");
					for (int j = 0; j < ssss.length; j++)
					{
						long gameID = 0;
						String[] so = ssss[j].split(",");
						if (j == 0)
						{
							gameID = Long.parseLong(so[0].substring(
								3).trim());
						}
						else
						{
							gameID = Long.parseLong(so[0]);
						}
						int state = Integer.parseInt(so[2]);
						String gameTime = so[3];
						String hostTeam = teamMap.get(Integer.parseInt(so[4]));
						String visitTeam = teamMap.get(Integer.parseInt(so[5]));
						String fullScore = so[6];
						String halfScore = so[7];
						// String sqlDelete =
						// "delete from game_result where game_id="+gameID;
						String sql = "insert into game_result (game_id, game_time, league_name, host_team, visit_team, half_score, full_score, round, state)"
							+ " values("
							+ gameID
							+ ",convert(datetime,"
							+ gameTime
							+ "),'"
							+ leagueName
							+ "','"
							+ hostTeam
							+ "','"
							+ visitTeam
							+ "',"
							+ halfScore
							+ "," + fullScore + ",'" + round + "'," + state + ")";
						// stmt.addBatch(sqlDelete);
						stmt.addBatch(sql);
					}

				}
			}
			while (line != null && !line.startsWith("var scoreColor"));
			stmt.executeBatch();
			da.close();
		}
		catch(Exception e)
		{
//			e.printStackTrace();
		}
		DBUtil.close(conn, stmt);

	}

	public String readSaichen(int ID, String season, String round)
		throws Exception
	{
		String u = "http://bf.bet007.com/phone/SaiCheng.aspx?ID=" + ID + "&Season=" + season
			+ "&Round=" + round.trim() + "&lang=0";
		URL url = new URL(u);
		URLConnection urlConn = url.openConnection();
		urlConn.connect();
		BufferedReader da = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),
			"UTF-8"));
		String line = da.readLine();
		da.close();
		return line;
	}

	public String getUpdatePankouResult(long gameID, String companyName, Connection conn, Statement stmt)
	{
		String sqlUpdate = null;
		try
		{
			double pankouInt = 0;
			double daxiaoPankouInt = 0;
			int hostGoals = 0;
			int visitGoals = 0;
			String pankouResult = "";
			String daxiaoResult = "";

			stmt = conn.createStatement();
			String sql = "select chupan_pankou,chupan_daxiao_pankou from game_detail_data where company_name='"+companyName+"' and game_id="
				+ gameID;
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				String pankou = rs.getString("chupan_pankou");
				String daxiaoPankou = rs.getString("chupan_daxiao_pankou");
				pankouInt = Double.parseDouble(pankou.trim());
				daxiaoPankouInt = Double.parseDouble(daxiaoPankou.trim());
			}
			else
			{
				rs.close();
				return null;
			}
			String sql1 = "select full_score from game_result where game_id=" + gameID;
			rs = stmt.executeQuery(sql1);
			if (rs.next())
			{
				String fullScore = rs.getString("full_score");
				String[] goals = fullScore.split("-");
				hostGoals = Integer.parseInt(goals[0].trim());
				visitGoals = Integer.parseInt(goals[1].trim());
			}
			rs.close();
			if (pankouInt >= 0)
			{
				if (hostGoals - visitGoals > pankouInt)
				{
					pankouResult = "赢";
				}
				else if (hostGoals - visitGoals == pankouInt)
				{
					pankouResult = "走";
				}
				else
				{
					pankouResult = "输";
				}
			}
			if (pankouInt < 0)
			{
				if (hostGoals - visitGoals < pankouInt)
				{
					pankouResult = "赢";
				}
				else if (hostGoals - visitGoals == pankouInt)
				{
					pankouResult = "走";
				}
				else
				{
					pankouResult = "输";
				}
			}
			if (hostGoals + visitGoals > daxiaoPankouInt)
			{
				daxiaoResult = "大";
			}
			else if (hostGoals + visitGoals == daxiaoPankouInt)
			{
				daxiaoResult = "走";
			}
			else
			{
				daxiaoResult = "小";
			}
			sqlUpdate = "update game_result set pankou_result = '" + pankouResult
				+ "', daxiao_result='" + daxiaoResult + "' where game_id=" + gameID;

		}

		catch (Exception e)
		{
//			System.out.println(gameID);
//			e.printStackTrace();
		}
		return sqlUpdate;
	}

	public void updateGameResultBySB()
	{
		Connection conn = DBUtil.getConnection();
		Statement stmt = null;
		try
		{
			stmt = conn.createStatement();
			String sql = "select game_id from game_result where state=-1 and pankou_result is null";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next())
			{
				long gameID = rs.getLong("game_id");
				String sqlUpdateResult = getUpdatePankouResult(
					gameID, "SB",conn, stmt);
				if (sqlUpdateResult != null)
					stmt.addBatch(sqlUpdateResult);
			}
			rs.close();
			stmt.executeBatch();
		}
		catch (Exception e)
		{
//			e.printStackTrace();
		}
		DBUtil.close(
			conn, stmt);
	}

	public void deleteGameResult()
	{
		Connection conn = DBUtil.getConnection();
		Statement stmt = null;
		try
		{
			stmt = conn.createStatement();
			String sql = "delete from game_result where state!=-1";
			stmt.executeUpdate(sql);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		DBUtil.close(
			conn, stmt);
	}
	
	public void importNewLeagueSaichen()
	{
		deleteGameResult();
		Properties props = new Properties();
		try
		{
			String name = "newLeagueSaichen.properties";
			InputStream in = new FileInputStream((CupGameResultManager.class.getResource("")+name).substring(6));
			props.load(in);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements())
			{
				String leagueName = (String) en.nextElement();
				String urlString = props.getProperty(leagueName);
				parseURL(
					leagueName, urlString);
			}
			in.close();
			updateGameResultBySB();
			updateGameResultByBet365();
		}
		catch (Exception e)
		{
//			e.printStackTrace();
		}
	}

	// 需要每天中午12点，把前24小时内结束的比赛结果更新到game_result表中
	public void updateGameResultByBet365()
	{
		Connection conn = DBUtil.getConnection();
		Statement stmt = null;
		try
		{
			stmt = conn.createStatement();
			ArrayList<Long> gameIDs = new ArrayList<Long>();
			String sql = "select game_id from game_result where state=-1 and pankou_result is null";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next())
			{
				long gameID = rs.getLong("game_id");
				gameIDs.add(gameID);
			}
			rs.close();
			int k = 0;
			for (long gameID : gameIDs)
			{
				String sqlUpdateResult = getUpdatePankouResult(
					gameID, "Bet365", conn, stmt);
				if(sqlUpdateResult!=null)
				{
					stmt.addBatch(sqlUpdateResult);
					k++;
				}
			}

			if (k > 0)
			{
				stmt.executeBatch();
			}
		}

		catch (Exception e)
		{
//			e.printStackTrace();
		}
		DBUtil.close(
			conn, stmt);
	}
}
